﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ThaireInvestmentWeb.Models;
using ThaireInvestmentWeb.Util;
using ThaireInvestmentWeb.WcfSerivce;

namespace ThaireInvestmentWeb.Controllers.Instrument
{
    public class DepositController : Controller
    {
        private WcfSerivce.InvestmentServiceClient _service;
        public WcfSerivce.InvestmentServiceClient Service
        {
            get { return _service ?? (_service = ServiceFactory.GetService()); }
        }

        #region ManageDepositHeader

        public ActionResult ManageDeposit(int? page)
        {
            ManageDepositModel model = new ManageDepositModel();
            try
            {
                if (page.GetValueOrDefault() == 0)
                {
                    var data = Service.GetDepositHeaderScreenData(null);
                    model = ManageDepositModel.BuildModel(data);
                }
                else //มาจาก page grid click
                {
                    model = (ManageDepositModel)TempData["ManageDepositModel"];
                }
            }
            catch (Exception ex)
            {
                model = new ManageDepositModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["ManageDepositModel"] = model;
            //return View("ManageDeposit", model);
            return View(model);
        }

        [HttpPost]
        public ActionResult ManageDeposit(ManageDepositModel model)
        {
            var oldModel = (ManageDepositModel)TempData["ManageDepositModel"];

            try
            {
                if (!String.IsNullOrEmpty(model.SearchBtn))
                {
                    var result = Service.SearchDeposit(model.SearchFilter);
                    if (result == null || result.Length == 0)
                    {
                        ViewBagUtil.SetDataNotFoundInfo(ViewBag);
                    }
                    else
                    {
                        oldModel.Result = result;
                    }
                }
                else if (!String.IsNullOrEmpty(model.ResetBtn))
                {
                    ModelState.Clear();
                    oldModel.ClearFilterAndData();
                }
                TempData["ManageDepositModel"] = oldModel;
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //return View("ManageDeposit", oldModel);
            return View(oldModel);
        }

        #endregion

        #region DepositHeader

        public ActionResult EditDepositHeader(int? headerId)
        {
            EditDepositHeaderModel model = null;
            try
            {
                var data = Service.GetDepositHeaderScreenData(headerId);
                model = EditDepositHeaderModel.BuildModel(data);
                if (data != null && data.HeaderDTO != null)
                    model.UpdateMode = true;
                TempData["EditDepositHeaderModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositHeaderModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult EditDepositHeader(EditDepositHeaderModel model)
        {
            var oldModel = (EditDepositHeaderModel)TempData["EditDepositHeaderModel"];
            //if (ModelState.IsValid)
            //{
            try
            {
                if (!String.IsNullOrEmpty(model.SaveBtn))
                {
                    var company = oldModel.CompanyList.SingleOrDefault(x => x.Value == model.Header.DepositCompanyID.GetValueOrDefault().ToString());
                    if (company != null)
                        model.Header.DepositCompanyName = company.Text;

                    //var DepositType = oldModel.DepositTypeList.SingleOrDefault(x => x.Value == model.Header.DepositTypeID.GetValueOrDefault().ToString());
                    //if (DepositType != null)
                    //    model.Header.DepositTypeID = int.Parse(DepositType.Value);

                    var involve = oldModel.InvolvedPartyTypeNameList.SingleOrDefault(x => x.Value == model.SelectedInvolvedPartyType.ToString());
                    if (involve != null)
                        model.Header.InvolvedPartyTypeName = involve.Text;

                    DepositHeaderDTO result = null;

                    if (model.UpdateMode)
                    {
                        model.Header.ModifyBY = ServiceFactory.UserId;
                        model.Header.CreateBY = oldModel.Header.CreateBY;
                        model.Header.CreateDate = oldModel.Header.CreateDate;
                        model.Header.ModifyDate = oldModel.Header.ModifyDate;

                        model.HeaderDTO.Rating.RatingHistoryId = oldModel.RatingHistory.RatingHistoryId;
                        model.HeaderDTO.Rating.FinancialInstrumentId = oldModel.RatingHistory.FinancialInstrumentId;
                        model.HeaderDTO.Rating.FinancialInstrumentType = oldModel.RatingHistory.FinancialInstrumentType;
                        model.HeaderDTO.Rating.FinancialInstrumentTypeID = oldModel.RatingHistory.FinancialInstrumentTypeID;
                        model.HeaderDTO.Rating.CreateUserId = oldModel.RatingHistory.CreateUserId;
                        model.HeaderDTO.Rating.CreateTs = oldModel.RatingHistory.CreateTs;

                        //model.HeaderDTO.Rating = model.RatingHistory;
                        result = Service.UpdateDepositHeader(model.HeaderDTO);
                    }
                    else
                    {
                        model.Header.CreateBY = ServiceFactory.UserId;
                        result = Service.InsertDepositHeader(model.HeaderDTO);
                    }
                    oldModel.Header = result.Header;
                    oldModel.Transactions = result.Transactions;
                    if (result.Rating != null)
                        oldModel.RatingHistory = result.Rating;
                    oldModel.UpdateMode = true;
                    ViewBagUtil.SetCompletedInfo(ViewBag);
                }
                else
                {
                    throw new Exception("Button save (BtnSave) is null.");
                }
            }
            catch (Exception ex)
            {
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //}
            TempData["EditDepositHeaderModel"] = oldModel;
            return View(oldModel);
        }

        public ActionResult GetInvolvedType(int id)
        {
            var oldModel = (EditDepositHeaderModel)TempData["EditDepositHeaderModel"];

            InvolvedPartyType involve = oldModel.ScreenData.InvolvedPartyTypes.Where(X => X.InvolvedPartyTypeId == id).SingleOrDefault();
            TempData["EditDepositHeaderModel"] = oldModel;
            if (involve != null)
            {
                return Json(new { InvolvedPartyTypeReference = involve.InvolvedPartyTypeReference, InvolvedPartyTypeCode = involve.InvolvedPartyTypeCode });
            }
            else
            {
                return Json(new { InvolvedPartyTypeReference = "", InvolvedPartyTypeCode = "" });
            }
        }
        public ActionResult FillBank(string bankCode, string br)
        {
            var oldModel = (EditDepositHeaderModel)TempData["EditDepositHeaderModel"];

            Bank bank = oldModel.BankBranchs.Where(x => x.BankCode == bankCode && x.BankBranchCode == br).SingleOrDefault();
            TempData["EditDepositHeaderModel"] = oldModel;
            if (bank != null)
            {
                return Json(new { BankCode = bank.BankCode });
            }
            else
            {
                return Json(new { BankCode = "" });
            }
        }

        public ActionResult GetMaturityStatus(DateTime? maturityDate)
        {
            if (maturityDate.GetValueOrDefault().Date >= DateTime.Now.Date)
                return Json(new { MaturityStatus = "Matured" });
            else
                return Json(new { MaturityStatus = "Alive" });
        }

        [HttpPost]
        public ActionResult GetBranch(string bankCode)
        {
            var oldModel = (EditDepositHeaderModel)TempData["EditDepositHeaderModel"];

            var branchs = Service.GetBranchByBankID(bankCode);
            if (branchs != null || branchs.Any())
            {
                //oldModel.BankBranchs.Clear();
                oldModel.BankBranchs = branchs;
            }

            TempData["EditDepositHeaderModel"] = oldModel;

            if (branchs != null && branchs.Length > 0)
            {
                var list = new System.ComponentModel.BindingList<SelectListItem>() { new SelectListItem() { Selected = false, Text = "--Select data--", Value = "" } };
                foreach (var selectListItem in branchs)
                {
                    list.Add(item: new SelectListItem() { Selected = false, Text = selectListItem.BankNameTh, Value = selectListItem.BankBranchCode });
                }
                return Json(new SelectList(list, "Value", "Text"));
            }
            else
            {
                var list = new System.ComponentModel.BindingList<SelectListItem>() { new SelectListItem() { Selected = false, Text = "--Select data--", Value = "" } };
                return Json(new SelectList(list, "Value", "Text"));
            }
        }

        public ActionResult GetCreditAgencyCountry(string rating, string credit)
        {
            var oldModel = (EditDepositHeaderModel)TempData["EditDepositHeaderModel"];

            var creditAgency = oldModel.ScreenData.IssueRatings.Where(x => x.CreditAgencyIssueRating == rating && x.CreditAgencyIssue == credit).SingleOrDefault();
            TempData["EditDepositHeaderModel"] = oldModel;
            
            if (creditAgency != null)
                return Json(new { CreditAgencyCountry = creditAgency.CreditAgencyCountry });
            return Json(new { CreditAgencyCountry = "" });

        }

        #endregion

        #region Deposit interest

        public ActionResult ViewInterestPaymentDate(int headerId)
        {
            AddDepositInterestModel model = null;
            try
            {
                var data = Service.GetDepositInterestScreenData(headerId);
                model = AddDepositInterestModel.BuildModel(data);
                //if (data != null && data.HeaderDTO != null)
                //    model.UpdateMode = true;
                TempData["AddDepositInterestModel"] = model;
            }
            catch (Exception ex)
            {
                model = new AddDepositInterestModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("ViewDepositInterestPaymentDate", model);
        }

        public ActionResult DeleteDepositInterestPaymentDate(int interestId)
        {
            AddDepositInterestModel oldModel = (AddDepositInterestModel)TempData["AddDepositInterestModel"];
            try
            {
                ServiceFactory.GetService().DeleteDepositInterest(interestId);
                var delItem = oldModel.InterestPaymentDateAdapters.Where(x => x.InterestID == interestId).SingleOrDefault();
                if (delItem != null)
                {
                    oldModel.InterestAdaters.Remove(delItem);
                }
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }

            TempData["AddDepositInterestModel"] = oldModel;

            return RedirectToAction("ViewInterestPaymentDate", "Deposit", new { headerId = oldModel.Header.DepositHeaderID, page = 0 });
        }


        public ActionResult EditInterestRate(int headerId)
        {
            AddDepositInterestModel model = null;
            try
            {
                var data = Service.GetDepositInterestScreenData(headerId);
                model = AddDepositInterestModel.BuildModel(data);
                //if (data != null && data.HeaderDTO != null)
                //    model.UpdateMode = true;
                TempData["AddDepositInterestModel"] = model;
            }
            catch (Exception ex)
            {
                model = new AddDepositInterestModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositInterestRate", model);
        }
        [HttpPost]
        public ActionResult EditInterestRate(AddDepositInterestModel model)
        {
            AddDepositInterestModel oldModel = (AddDepositInterestModel)TempData["AddDepositInterestModel"];

            try
            {
                var service = ServiceFactory.GetService();
                if (!String.IsNullOrEmpty(model.BtnSubmit))
                {
                    DepositInterest data = new DepositInterest();
                    //data. = SessionManager.UserID(Session);
                    //data.PaymentDate = model.PaymentDate;
                    data.InterestApplyDate = model.ApplyDate;
                    data.InterestRate = model.InterestRate;
                    data.DepositHeaderID = oldModel.HeaderID;
                    data = service.InsertDepositInterest(data);

                    oldModel.InterestAdaters.Add(new DepositInterestAdapter(data));
                    ModelState.Clear();
                }
                //else if (model.DeleteID.HasValue)
                //{
                //    service.DeleteAmortizeSchedule(model.DeleteID.Value);
                //    var delItem = oldModel.ScheduleList.Where(x => x.FixincomesecuritiesAmortizeScheduleID == model.DeleteID.Value).SingleOrDefault();
                //    if (delItem != null)
                //    {
                //        oldModel.ScheduleList.Remove(delItem);
                //    }
                //    ModelState["DeleteID"].Value = null;//clear stage
                //}
                //else
                //{
                //    ViewBagUtil.SetError(ViewBag, "Unknow Operation", null);
                //}
            }
            catch (Exception ex)
            {

                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }

            TempData["AddDepositInterestModel"] = oldModel;
            return RedirectToAction("EditInterestRate", "Deposit", new { headerId = oldModel.HeaderID, page = 0 });
        }

        public ActionResult DeleteDepositInterest(int interestId)
        {
            AddDepositInterestModel oldModel = (AddDepositInterestModel)TempData["AddDepositInterestModel"];
            try
            {
                ServiceFactory.GetService().DeleteDepositInterest(interestId);
                var delItem = oldModel.InterestAdaters.Where(x => x.InterestID == interestId).SingleOrDefault();
                if (delItem != null)
                {
                    oldModel.InterestAdaters.Remove(delItem);
                }
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }

            TempData["AddDepositInterestModel"] = oldModel;

            return RedirectToAction("EditInterestRate", "Deposit", new { headerId = oldModel.Header.DepositHeaderID, page = 0 });
        }

        #endregion

        #region Transaction -->Deposit

        public ActionResult AddDepositTransaction(int headerId)
        {
            EditDepositTransactionModel model = null;
            try
            {
                var data = Service.GetDepositTransactionScreenData(headerId, null, "Deposit");
                model = EditDepositTransactionModel.BuildModel(data);
                TempData["EditDepositTransactionModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositTransactionModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositTransaction", model);
        }

        public ActionResult EditDepositTransaction(int transactionId)
        {
            EditDepositTransactionModel model = null;
            try
            {
                var data = Service.GetDepositTransactionScreenData(null, transactionId, "Deposit");
                model = EditDepositTransactionModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditDepositTransactionModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositTransactionModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositTransaction", model);
        }

        [HttpPost]
        public ActionResult EditDepositTransaction(EditDepositTransactionModel model)
        {
            var oldModel = (EditDepositTransactionModel)TempData["EditDepositTransactionModel"];
            //if (ModelState.IsValid)
            //{
            try
            {
                if (!String.IsNullOrEmpty(model.SubmitBtn))
                {
                    if (model.UpdateMode)
                    {
                        model.Transaction.ModifyBY = ServiceFactory.UserId;
                        model.Transaction.CreateBY = oldModel.Transaction.CreateBY;
                        model.Transaction.CreateDate = oldModel.Transaction.CreateDate;
                        model.Transaction.ModifyDate = oldModel.Transaction.ModifyDate;
                        oldModel.Transaction = Service.UpdateDepositTransaction(model.Transaction);
                    }
                    else
                    {
                        model.Transaction.CreateBY = ServiceFactory.UserId;
                        oldModel.Transaction = Service.InsertDepositTransaction(model.Transaction);
                    }
                    oldModel.UpdateMode = true;
                    ViewBagUtil.SetCompletedInfo(ViewBag);
                }
                else
                {
                    throw new Exception("Button save (BtnSave) is null.");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //}
            TempData["EditDepositTransactionModel"] = oldModel;
            return View("EditDepositTransaction", oldModel);
        }
        #endregion

        #region Transaction -->Withdraw

        public ActionResult AddWithdrawTransaction(int headerId)
        {
            EditDepositWithdrawTransactionModel model = null;
            try
            {
                var data = Service.GetDepositTransactionScreenData(headerId, null, "Withdraw");
                model = EditDepositWithdrawTransactionModel.BuildModel(data);
                TempData["EditDepositWithdrawTransactionModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositWithdrawTransactionModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositWithdrawTransaction", model);
        }

        public ActionResult EditDepositWithdrawTransaction(int transactionId)
        {
            EditDepositWithdrawTransactionModel model = null;
            try
            {
                var data = Service.GetDepositTransactionScreenData(null, transactionId, "Withdraw");
                model = EditDepositWithdrawTransactionModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditDepositWithdrawTransactionModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositWithdrawTransactionModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositWithdrawTransaction", model);
        }

        [HttpPost]
        public ActionResult EditDepositWithdrawTransaction(EditDepositWithdrawTransactionModel model)
        {
            var oldModel = (EditDepositWithdrawTransactionModel)TempData["EditDepositWithdrawTransactionModel"];
            //if (ModelState.IsValid)
            //{
            try
            {
                if (!String.IsNullOrEmpty(model.SubmitBtn))
                {
                    if (model.UpdateMode)
                    {
                        model.Transaction.ModifyBY = ServiceFactory.UserId;
                        model.Transaction.CreateBY = oldModel.Transaction.CreateBY;
                        model.Transaction.CreateDate = oldModel.Transaction.CreateDate;
                        model.Transaction.ModifyDate = oldModel.Transaction.ModifyDate;
                        oldModel.Transaction = Service.UpdateDepositTransaction(model.Transaction);
                    }
                    else
                    {
                        model.Transaction.CreateBY = ServiceFactory.UserId;
                        oldModel.Transaction = Service.InsertDepositTransaction(model.Transaction);
                    }
                    oldModel.UpdateMode = true;
                    ViewBagUtil.SetCompletedInfo(ViewBag);
                }
                else
                {
                    throw new Exception("Button save (BtnSave) is null.");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //}
            TempData["EditDepositWithdrawTransactionModel"] = oldModel;
            return View("EditDepositWithdrawTransaction", oldModel);
        }
        #endregion

        #region Transaction -->Guarantee

        public ActionResult AddGuaranteeTransaction(int headerId)
        {
            EditDepositGuaranteeTransactionModel model = null;
            try
            {
                var data = Service.GetDepositTransactionScreenData(headerId, null, "Guarantee");
                model = EditDepositGuaranteeTransactionModel.BuildModel(data);
                TempData["EditDepositGuaranteeTransactionModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositGuaranteeTransactionModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositGuaranteeTransaction", model);
        }

        public ActionResult EditDepositGuaranteeTransaction(int transactionId)
        {
            EditDepositGuaranteeTransactionModel model = null;
            try
            {
                var data = Service.GetDepositTransactionScreenData(null, transactionId, "Guarantee");
                model = EditDepositGuaranteeTransactionModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditDepositGuaranteeTransactionModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditDepositGuaranteeTransactionModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditDepositGuaranteeTransaction", model);
        }

        [HttpPost]
        public ActionResult EditDepositGuaranteeTransaction(EditDepositGuaranteeTransactionModel model)
        {
            var oldModel = (EditDepositGuaranteeTransactionModel)TempData["EditDepositGuaranteeTransactionModel"];
            //if (ModelState.IsValid)
            //{
            try
            {
                if (!String.IsNullOrEmpty(model.SubmitBtn))
                {
                    if (model.UpdateMode)
                    {
                        model.Transaction.ModifyBY = ServiceFactory.UserId;
                        model.Transaction.CreateBY = oldModel.Transaction.CreateBY;
                        model.Transaction.CreateDate = oldModel.Transaction.CreateDate;
                        model.Transaction.ModifyDate = oldModel.Transaction.ModifyDate;
                        oldModel.Transaction = Service.UpdateDepositTransaction(model.Transaction);
                    }
                    else
                    {
                        model.Transaction.CreateBY = ServiceFactory.UserId;
                        oldModel.Transaction = Service.InsertDepositTransaction(model.Transaction);
                    }
                    oldModel.UpdateMode = true;
                    ViewBagUtil.SetCompletedInfo(ViewBag);
                }
                else
                {
                    throw new Exception("Button save (BtnSave) is null.");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //}
            TempData["EditDepositGuaranteeTransactionModel"] = oldModel;
            return View("EditDepositGuaranteeTransaction", oldModel);
        }
        #endregion

    }
}
